package com.zzyl.nursing.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-12
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginVo login(UserLoginRequestDto dto) {
        //1.根据code调用微信api获取apenId
        String openId = wechatService.getOpenId(dto.getCode());
        //2.根据openId查询数据库获取用户信息family_member表
        FamilyMember familyMember = familyMemberMapper.selectOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getOpenId, openId));
        //3.判断用户信息是否存在，如果不存在，则新增family_member表，存在则修改
        if (ObjectUtils.isEmpty(familyMember)) {
            familyMember = FamilyMember.builder().openId(openId).build();
        }
        //4.调用微信api获取用户绑定手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        //5.新增或者修改family_member表数据
        insertOrUpdate(familyMember, phone);
        //6.将用户id存入token中，并返回数据给前端
        HashMap<String, Object> clams = new HashMap<>();
        clams.put("userId", familyMember.getId());
        clams.put("nickName", familyMember.getName());
        String token = tokenService.createToken(clams);
        LoginVo loginVo = LoginVo.builder()
                .token(token)
                .nickName(familyMember.getName())
                .build();
        return loginVo;
    }

    private void insertOrUpdate(FamilyMember familyMember, String phone) {
        //判断手机号是否变化，如果变化则更新
        if (!Objects.equals(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断family_member表id是否为空，如果为空则新增，不为空则修改
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(familyMember.getPhone(), 7);
            familyMember.setName(nickName);
            save(familyMember);
        } else {
            updateById(familyMember);
        }
    }
}
